/**
 * Copyright (C) 2011 Vinicius Vielmo Cogo, Marcelo Pasin, and the authors
 * indicated in the @author tags.
 * 
 * This file is part of DiversityAgent.
 * 
 * DiversityAgent is a free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 * 
 * DiversityAgent is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with DiversityAgent. If not, see <http://www.gnu.org/licenses/>.
 */
package diversities;

import java.util.ArrayList;
import java.util.Properties;

import diversity_agent.DataContainer;
import diversity_agent.VirtualMachine;

/**
 * 
 * @author Vinicius Vielmo Cogo (vielmo at lasige.di.fc.ul.pt)
 * @version 0.1-beta
 * @since 2011-11-18
 * 
 */
public class Hostname extends diversity_agent.Diversity
{

	public Hostname()
	{
		mDiversityAxis = diversity_agent.DIVERSITY_AXIS.ADMINISTRATIVE;
		mDependencies.add("cloud.name"); // not used yet
	}

	@Override
	public Properties getContribution(Properties theProperties,
			DataContainer theDataContainer)
	{
		if (theProperties.getProperty("host.name.equal") != null) {
			return theProperties;
		}

		ArrayList<VirtualMachine> aVmList = theDataContainer.retrieveVms();

		String aCloudName = theProperties.getProperty("cloud.name");
		if (aCloudName == null) {
			aCloudName = theDataContainer.retrieveAnyCloud().getCloudName();
			theProperties.setProperty("cloud.name", aCloudName);
		}

		StringBuilder aUsedHostsList = new StringBuilder();
		int i = 0;
		for (VirtualMachine aVm : theDataContainer.retrieveVms()) {
			if (aCloudName.equals(aVm.getCloudName())) {
				if (aUsedHostsList.indexOf(aVm.getHostName()) == -1) {
					aUsedHostsList.append(aVm.getHostName());
				}
				if (i < aVmList.size() - 1) {
					aUsedHostsList.append(",");
				}
			}
			i++;
		}

		// Adding the property
		if (!aUsedHostsList.toString().equals("")) {
			theProperties.setProperty("host.name.differ", aUsedHostsList
					.toString());
		}

		// Returning the new set of properties
		return theProperties;
	}
}
